package com.am.server.api.system.upload.controller;

import com.am.server.api.system.upload.config.LocalFileUploadConfig;
import com.am.server.api.system.upload.enumerate.FileType;
import com.am.server.api.system.upload.exception.DownloadFileException;
import com.am.server.api.system.upload.model.dto.SysFileUrlDto;
import com.am.server.api.system.upload.model.dto.UploadResultDto;
import com.am.server.api.system.upload.model.entity.SysFileEntity;
import com.am.server.api.system.upload.service.SysFileService;
import com.am.server.common.constant.Constant;
import com.am.server.common.util.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 文件上传
 *
 * @author 阮雪锋
 */
@Slf4j
@Controller
@RequestMapping(Constant.ADMIN_ROOT)
public class UploadController {

    private final SysFileService sysFileService;
    private final LocalFileUploadConfig localFileUploadConfig;

    public UploadController(SysFileService sysFileService, LocalFileUploadConfig localFileUploadConfig) {
        this.sysFileService = sysFileService;
        this.localFileUploadConfig = localFileUploadConfig;
    }

    /**
     * 文件上传
     *
     * @param file 文件对象
     * @param type 文件类型
     * @return ResponseEntity
     */
    @PostMapping("/upload")
    public ResponseEntity<UploadResultDto> upload(MultipartFile file, FileType type) {
        return ResponseUtils.ok(sysFileService.save(file, type));
    }

    @GetMapping("/url/{id}")
    public ResponseEntity<SysFileUrlDto> url(@PathVariable Long id) {
        return ResponseUtils.ok(new SysFileUrlDto(sysFileService.findById(id).getUrl()));
    }

    @PostMapping("/download/{id}")
    public void download(@PathVariable Long id, HttpServletResponse response) {
        SysFileEntity entity = sysFileService.findById(id);
        try (FileInputStream fileInputStream = new FileInputStream(String.format("%s%s%s", localFileUploadConfig.getFilePath(), File.separator, entity.getDir()))) {
            byte[] body = fileInputStream.readAllBytes();
            response.addHeader("Content-Disposition", "attachment;filename=" + entity.getFileName());
            response.setContentLength(body.length);
            //获取Servlet的输出流ServletOutputStream
            ServletOutputStream sos = response.getOutputStream();
            sos.write(body);
            sos.close();
        } catch (IOException e) {
            log.error(String.format("下载文件%s（%s）发生异常", entity.getFileName(), entity.getId()), e);
            throw new DownloadFileException(String.format("下载文件%s发生出错", entity.getFileName()), e);
        }
    }
}
